package com.elitel.common.businessJdbc.sqlserver;

import com.elitel.common.businessJdbc.BusinessScriptPreparedStatement;

public class SqlServerScriptPreparedStatement extends BusinessScriptPreparedStatement{
   @Override
    public String getPrecompileSql(){
        // here is page or not pageable
        StringBuilder sb = new StringBuilder();
        sb.append(getSqlWithPlaceHolder());

        if(isPageable()){
            // here is judge order by
            if(!checkKeywordOfOrderBy(getSqlWithPlaceHolder()))
                sb.append(" order by (select null) ");

            sb.append(" offset ")
                .append( (pageNumber - 1) * pageSize)
                .append(" rows fetch next ")
                .append(pageSize)
                .append(" rows only ");
        }

        return sb.toString();
    }

    // here is check if existed order by keyword
    // if existed remove order by until final
    //    -- here is check sqlWithPlaceHolder delete order by until final
    //
    @Override
    public String getPrecompileCountSql(){
        // here is check order by keyword
        String sqlWithPlaceHolder = getSqlWithPlaceHolder();
        if(checkKeywordOfOrderBy(sqlWithPlaceHolder)){
            // here find order by index , and get first to here length - 1
            int index = sqlWithPlaceHolder.indexOf("order by");
            if(index != -1){
                sqlWithPlaceHolder = sqlWithPlaceHolder.substring(0, index);
            }
        }

        StringBuilder sb = new StringBuilder();
        sb.append(" select count(*) from ( ")
            .append(sqlWithPlaceHolder)
            .append(" ) a ");
        return sb.toString();
    }

    private static boolean checkKeywordOfOrderBy(String sqlStatement){
        if(sqlStatement == null)
            return false;

        return sqlStatement.toLowerCase().contains("order by");
    }

    // public static void main(String[] args){
    //     // here is check order by keyword
    //     String sqlWithPlaceHolder = "select count(*) from table_a where 1=1!order by hello desc ";
    //     System.out.println(sqlWithPlaceHolder);

    //     if(checkKeywordOfOrderBy(sqlWithPlaceHolder)){
    //         // here find order by index , and get first to here length - 1
    //         int index = sqlWithPlaceHolder.indexOf("order by");
    //         if(index != -1){
    //             sqlWithPlaceHolder = sqlWithPlaceHolder.substring(0, index);
    //         }
    //     }

    //     StringBuilder sb = new StringBuilder();
    //     sb.append(" select count(*) from ( ")
    //         .append(sqlWithPlaceHolder)
    //         .append(" ) a ");
    //     System.out.println(sb.toString());

    // }
}
